#!/usr/bin/env python3
"""
MySQL MCP 客户端 - 简单易用版本
使用方法：
1. 复制此文件到您的项目中
2. 确保MySQL MCP服务在 http://localhost:8099 运行
3. 直接调用方法即可
"""

import requests
import json
from typing import List, Dict, Any, Optional

class SimpleMySQLClient:
    def __init__(self, base_url: str = "http://localhost:8099"):
        self.base_url = base_url
        self.request_id = 0
    
    def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None) -> Any:
        """调用MCP工具"""
        if args is None:
            args = {}
        
        self.request_id += 1
        request = {
            "jsonrpc": "2.0",
            "id": str(self.request_id),
            "method": "tools/call",
            "params": {
                "name": name,
                "arguments": args
            }
        }
        
        response = requests.post(f"{self.base_url}/mcp/call", json=request)
        response.raise_for_status()
        
        result = response.json()
        if "error" in result and result["error"]:
            raise Exception(f"MCP错误: {result['error']['message']}")
        
        return result["result"]
    
    # 基础方法
    def test_connection(self) -> Dict[str, Any]:
        """测试数据库连接"""
        return self.call_tool("test_connection")
    
    def list_tables(self) -> Dict[str, Any]:
        """获取所有表列表"""
        return self.call_tool("list_tables")
    
    def query(self, sql: str, params: Optional[List[Any]] = None) -> Dict[str, Any]:
        """执行查询"""
        if params is None:
            params = []
        return self.call_tool("query", {"sql": sql, "params": params})
    
    def execute(self, sql: str, params: Optional[List[Any]] = None) -> Dict[str, Any]:
        """执行更新操作"""
        if params is None:
            params = []
        return self.call_tool("execute", {"sql": sql, "params": params})
    
    def describe_table(self, table_name: str) -> Dict[str, Any]:
        """获取表结构"""
        return self.call_tool("describe_table", {"table": table_name})
    
    # 高级便捷方法
    def get_table_data(self, table_name: str, limit: int = 10) -> Dict[str, Any]:
        """获取表数据"""
        return self.query(f"SELECT * FROM {table_name} LIMIT {limit}")
    
    def get_table_structure(self, table_name: str) -> Dict[str, Any]:
        """获取表结构"""
        return self.describe_table(table_name)
    
    def find_tables_by_pattern(self, pattern: str) -> List[str]:
        """根据模式查找表"""
        tables = self.list_tables()
        return [table for table in tables["tables"] 
                if pattern.lower() in table.lower()]
    
    def get_user_tables(self) -> List[str]:
        """获取用户相关表"""
        return self.find_tables_by_pattern("user")
    
    def get_system_tables(self) -> List[str]:
        """获取系统相关表"""
        return self.find_tables_by_pattern("sys_")
    
    def get_config_tables(self) -> List[str]:
        """获取配置相关表"""
        return self.find_tables_by_pattern("config")

# 使用示例
def example():
    """使用示例"""
    db = SimpleMySQLClient()
    
    try:
        # 测试连接
        print("连接状态:", db.test_connection())
        
        # 获取所有表
        tables = db.list_tables()
        print(f"数据库共有 {tables['count']} 个表")
        
        # 获取用户表数据
        users = db.get_table_data("sys_user", 5)
        print(f"用户数据: {len(users['rows'])} 条记录")
        
        # 获取表结构
        structure = db.get_table_structure("sys_user")
        print(f"用户表有 {len(structure['structure'])} 个字段")
        
        # 查找用户相关表
        user_tables = db.get_user_tables()
        print("用户相关表:", user_tables)
        
        # 查找系统表
        system_tables = db.get_system_tables()
        print(f"系统表数量: {len(system_tables)}")
        
    except Exception as e:
        print(f"操作失败: {e}")

if __name__ == "__main__":
    example() 